#pragma once
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "MyPthread/Log.hpp"
#include "Common.hpp"
using namespace LogModule;

class InetAddr
{
private:
    // 端口本地转网络
    void PortNet2Host()
    {
        _port = ::ntohs(_net_addr.sin_port);
    }
    // ip本地转网络
    void IpNet2Host()
    {
        char ipbuffer[64];
        
        // _ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        
        
        const char*  result = ::inet_ntop(AF_INET, &_net_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        if (result == nullptr)
        {
            // 转换失败，打印错误原因
            LOG(LogLevel::ERROR) << "inet_ntop failed: " << strerror(errno);
            _ip = ""; // 显式设为空
        }
        else
        {
            // 转换成功，正常赋值
            _ip = result; // 等价于 _ip = ipbuffer
            // LOG(LogLevel::DEBUG) << "IpNet2Host ip : " << _ip;
        }
    }
    // void IpNet2Host()
    // {
    //     char ipbuffer[64];
    //     const char *ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
    //     (void)ip;
    //     _ip = ipbuffer;
    // }

public:
    // InetAddr(std::string ip, uint16_t port)
    //     : _ip(ip), _port(port)
    // {
    // }

    InetAddr(const struct sockaddr_in &addr) : _net_addr(addr)
    {
        PortNet2Host();
        IpNet2Host();
    }
    InetAddr(uint16_t port) : _port(port), _ip("")
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = htons(_port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }
    InetAddr(std::string ip, uint16_t port) : _port(port), _ip(ip)
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = htons(_port);
        _net_addr.sin_addr.s_addr = ::inet_addr(_ip.c_str());
    }
    struct sockaddr *NetAddr() { return CONV(&_net_addr); }
    socklen_t NetAddrLen() { return sizeof(_net_addr); }
    std::string Ip() const { return _ip; }
    uint16_t Port() const { return _port; }

    bool operator==(const InetAddr &addr)
    {
        return this->Ip() == addr.Ip() && this->Port() == addr.Port();
    }
    std::string Addr()
    {
        return Ip() + ":" + std::to_string(Port());
    }
    ~InetAddr()
    {
    }

private:
    struct sockaddr_in _net_addr;
    std::string _ip;
    uint16_t _port;
};